package by.dvrudenko.avtobaza.webapp.page.driver.panel;

import java.util.Iterator;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.resource.UrlResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.dvrudenko.avtobaza.datamodel.Driver;
import by.dvrudenko.avtobaza.datamodel.Driver_;
import by.dvrudenko.avtobaza.services.DriverService;
import by.dvrudenko.avtobaza.webapp.page.AbstractPanel;
import by.dvrudenko.avtobaza.webapp.page.car.panel.MyPagingNavigator;
import by.dvrudenko.avtobaza.webapp.page.createDriver.CreateDriverPage;
import by.dvrudenko.avtobaza.webapp.utils.security.SecuredLinkForAdmin;
import by.dvrudenko.avtobaza.webapp.utils.security.SecuredLinkForAdminAjax;

public class DriverListPanel extends AbstractPanel {

	private static final Logger LOGGER = LoggerFactory.getLogger(DriverListPanel.class);	
	
	@Inject
	private DriverService driverService;
	
	public DriverListPanel(String id) {
		super(id);
		setOutputMarkupId(true);
		DriverDataProvider driverDataProvider = new DriverDataProvider();

		final WebMarkupContainer tableBody = new WebMarkupContainer("wrapper-body"); 
		add(tableBody);
		// таблица для вывода водителей
		DataView<Driver> dataView = new DataView<Driver>("list", driverDataProvider, 5) {
			@Override
			protected void populateItem(Item<Driver> item) {
				final Driver driver = item.getModelObject();				
				
				item.add(new Label("user.name"));				
				item.add(new Label("lastName"));
				item.add(new Label("birthday" , handleYearFromCurrent(driver.getAge())));
				item.add(new Label("experience", handleYearFromCurrent(driver.getExperience())));			
				item.add(new Label("work", handleValueDriverWork(driver)));
				
				// добавляем картинку
				final String urlStr = getImageDriver(driver);
		        final UrlResourceReference url= new UrlResourceReference(Url.parse(urlStr));
		        item.add(new Image("wrapper-img", url));
								
				item.add(new Label("acomplishRoutes"));

				item.add(new SecuredLinkForAdmin("edit") {
					@Override
					public void onClick() {
						setResponsePage(new CreateDriverPage(driver, driver.getUser()));
					}
				});
				
				//  ссылка для удаления
				item.add(new SecuredLinkForAdminAjax("remove-ajax") {
					@Override
					public void onClick(AjaxRequestTarget target) {
						driverService.delete(driver);
						LOGGER.info("delete Driver, userLogin - "+user.getLogin());
						info(new ResourceModel("p.home.driver.panel.deleteDriver").getObject().toString());
						target.addChildren(getPage(), FeedbackPanel.class);	
						target.add(DriverListPanel.this);
					}
					
					// если водитель уехал, то его удалить нельзя
					@Override
					protected void onConfigure() {
						super.onConfigure();
						if (!driver.getWork().equals(false)){
							setVisible(false);
						};
					}

				});

			}
		};

		tableBody.add(dataView);

		add(new MyPagingNavigator("paging", dataView));

		add(new OrderByBorder<SingularAttribute<Driver, ?>>("sortByLastName", Driver_.lastName, driverDataProvider));
		add(new OrderByBorder<SingularAttribute<Driver, ?>>("sortByBirthday", Driver_.birthday, driverDataProvider));
		add(new OrderByBorder<SingularAttribute<Driver, ?>>("sortByExperience", Driver_.experience, driverDataProvider));
			
	}

	private class DriverDataProvider extends SortableDataProvider<Driver, SingularAttribute<Driver, ?>> {

		public DriverDataProvider() {
			super();
			setSort(Driver_.lastName, SortOrder.ASCENDING);
		}

		@Override
		public Iterator<? extends Driver> iterator(long first, long count) {
			SingularAttribute<Driver, ?> sortParam = getSort().getProperty();
			SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
			boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
			return driverService.getAllDrivers(sortParam, ascending, (int) first, (int) count).iterator();
		}

		@Override
		public long size() {
			return driverService.getCount();
		}

		@Override
		public IModel<Driver> model(Driver driver) {
			return new CompoundPropertyModel<Driver>(driver);
		}
	}

}
